package com.lagou.distribution.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public SecurityInterceptor getSecurityInterceptor() {
        return new SecurityInterceptor();
    }


    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        //默认到登陆页
        registry.addViewController("/").setViewName("forward:/toLogin");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        InterceptorRegistration addInterceptor = registry.addInterceptor(getSecurityInterceptor());
        //排除配置
        addInterceptor.addPathPatterns("/**").excludePathPatterns("/login", "/toLogin");

    }

    private class SecurityInterceptor extends HandlerInterceptorAdapter {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException, IOException {
            HttpSession session = request.getSession();
            //判断是否已有该用户登录的session
            if ("true".equals(session.getAttribute("isLogin"))) {
                return true;
            }
            //跳转到登录页
            String url = "/toLogin";
            response.sendRedirect(url);
            return false;
        }
    }

}
